var matchResults = [],
	passRate = 55;
const MAX_SIZE = 3;
const m = 100;
var iterateFinished = false;
function gray(imgData, cxt) {
	var arr = [];
	for(var i = 0; i < imgData.data.length; i += 4) {
		var R = imgData.data[i],
			G = imgData.data[i + 1],
			B = imgData.data[i + 2],
			Alpha = imgData.data[i + 3],
			gray = parseInt((R * 299 + G * 587 + B * 114 + 500) / 1000);
		imgData.data[i] = gray;
		imgData.data[i + 1] = gray;
		imgData.data[i + 2] = gray;
		imgData.data[i + 3] = Alpha;
		arr.push(imgData.data[i]);　
	}
	return arr;
}

function MatchImg(canvasID, cname, imgSrc, size, srcArr, iterate, limit, round) {
	console.log("============ " + iterate + " ============ limit: " + limit);
	round = round || limit;
	if (iterate <= round && iterate <= limit) {
		var results = [];
		var c = document.getElementById(canvasID),
			cxt = c.getContext("2d"),
			start = iterate * m,
			end = (iterate + 1) * m,
			srcArrMin = srcArr.slice(start, end);
		console.log(srcArrMin);
		var img1 = new Image();
		if (imgSrc.length < 100) {
			img1.src = "./images/" + cname + "/" + imgSrc + ".jpg";
		} else {
			img1.src = imgSrc;
		}
		var	n = size,
			w = n,
			h = n,
			x1 = 0,
			y1 = 0,
			x2 = n,
			y2 = 0,
			delta = n,
			rowNum = parseInt((300 - n) / n);
		
		var compareArr1;
		var sim = [];
		var imgs = [];
		
		img1.onload = function() {
			cxt.drawImage(img1, x1, y1, w, h);
			var RGB1 = cxt.getImageData(x1, y1, w, h);
			compareArr1 = gray(RGB1, cxt);
		}
		
		function nextSrc(srcArrMin, sig, cname) {
			if(sig == srcArrMin.length) return;
			var img = new Image();
			img.onload = function() {
				var row = parseInt(sig / rowNum),
					col = sig % rowNum,
					posX = x2 + delta * col,
					posY = y2 + delta * row;
				cxt.drawImage(img, posX, posY, w, h);
				var RGB1 = cxt.getImageData(posX, posY, w, h);
				imgs.push(gray(RGB1, cxt));
				nextSrc(srcArrMin, sig + 1, cname);
			}
			if(srcArrMin[sig].indexOf(".jpg") >= 0) {
				img.src = "./images/" + cname + "/" + srcArrMin[sig];
			} else {
				img.src = "./images/" + cname + "/" + srcArrMin[sig] + ".jpg";
			}
		}
		nextSrc(srcArrMin, 0, cname);
		
		var interval = setInterval(function() {
			if(compareArr1 && imgs.length == srcArrMin.length) {
				for(var j = 0; j < srcArrMin.length; j++) {
					var sum = 0;
					var l = compareArr1.length;
					for(var i = 0; i < l; i++) {
						sum += Math.abs(compareArr1[i] - imgs[j][i]);
					}
					var p = 100 - (sum / (w * h));
					console.log(p);
					if(p >= passRate) {
						sim.push(p);
						results.push(srcArrMin[j]);
						matchResults.push(srcArrMin[j]);
					}
				}
				console.log(results);
				clearInterval(interval);
				cxt.clearRect(0, 0, c.width, c.height);
				MatchImg(canvasID, cname, imgSrc, size, srcArr, iterate + 1, limit, round);
			}
		
		}, 1000);
	} else {
		iterateFinished = true;
		return;
	}
}